<template>
  <div>
    <el-upload
      ref="upload"
      class="upload-demo"
      action=""
      :multiple="false"
      :http-request="customUpload"
      :on-change="handleChange"
      :accept="'.bpmn20.xml'"
      :auto-upload="false"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      <div slot="tip" class="el-upload__tip">只能上传.bpmn20.xml文件</div>
    </el-upload>
  </div>
</template>

<script>
  import { upload } from '@/api/file'
  export default {
    data() {
      return {
        bpmnFile: null,
        bpmn: '',
        processDesign: {
          processDefinitionPath: ''
        }
      }
    },
    methods: {
      handleChange(file, fileList) {
        if (this.beforeUpload(file.raw)) {
          // 清空已有的文件列表
          this.$refs.upload.clearFiles()
          // 更新 bpmnFile 和 bpmn 变量
          this.bpmnFile = file.raw
          this.bpmn = URL.createObjectURL(file.raw)
          // 直接将新选中的文件设置为唯一的文件
          this.$nextTick(() => {
            this.$refs.upload.uploadFiles = [file]
          })
        } else {
          // 如果文件不满足条件，则清空已选文件列表
          this.$refs.upload.clearFiles()
        }
      },
      beforeUpload(file) {
        const isBPMN = file.name.toLowerCase().endsWith('.bpmn20.xml')
        if (!isBPMN) {
          this.$message.error('只能上传.bpmn20.xml格式的文件!')
        }
        return isBPMN
      },
      async customUpload(options) {
        const formData = new FormData()
        formData.append('file', options.file)
        this.processDesign.processDefinitionPath = await upload(formData) // 假设upload函数返回一个Promise
        this.$message.success('文件上传成功')
        // 将数据保存到vuex中
        this.$store.dispatch('approval/setProcessDesign', this.processDesign)
      },
      submitUpload() {
        this.$refs.upload.submit()
      }
    }
  }
</script>
